package com.whisperarts.financer.app.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import com.whisperarts.financer.app.Application;
import com.whisperarts.financer.app.utils.UIUtils;
import com.whisperarts.financer.dao.AccountsDAO;
import com.whisperarts.financer.model.account.Account;
import com.whisperarts.financer.model.transaction.Transaction;

public class DeleteTransactionAction extends Action implements 
	ISelectionListener, IWorkbenchAction {
	
	private final IWorkbenchWindow window;
	public final static String ID = "com.whisperarts.financer.app.actions.deleteTransaction";
	private IStructuredSelection selection;
	
	
	public DeleteTransactionAction(IWorkbenchWindow window) {
		this.window = window;
		setId(ID);
		setText("&Delete transaction");
		setToolTipText("Delete selected transaction");
		setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(Application.PLUGIN_ID, ISharedImages.IMG_ELCL_REMOVE));
		window.getSelectionService().addSelectionListener(this);
	}
	
	@Override
	public void selectionChanged(IWorkbenchPart part, ISelection incoming) {		
		if (incoming instanceof IStructuredSelection) {			
			selection = (IStructuredSelection) incoming;
			setEnabled(selection.size() == 1 
					&& selection.getFirstElement() instanceof Transaction);
		} else {
			setEnabled(false);
		}
	}
	
	@Override
	public void dispose() {
		window.getSelectionService().removeSelectionListener(this);
	}
	
	@Override
	public void run() {
		Transaction tx = (Transaction) selection.getFirstElement();
		
		if (MessageDialog.openConfirm(window.getShell(), "Delete transaction", "Do you really want to delete selected transaction?")) {
			if (AccountsDAO.deleteTransaction(tx) == 0) {
				Account account = AccountsDAO.getAccountById(tx.getAccountId());
				account.getTransactions().remove(tx);
				UIUtils.updateActiveEditor(window, account);
			}
		}
	}
}
